package com.zahb.qadx.ui.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.ExercisesDaily;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.activity.topic.DailyPracticeActivity;
import com.zahb.qadx.util.ClickCheck;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.PackageUtils;
import com.zahb.qadx.util.Tips;
import com.zahb.qadx.util.WebViewHelper;
import com.zahb.qadx.webview.MyWebViewActivity;

import org.jetbrains.annotations.NotNull;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 答题练习
 */
public class AnswerExercisesActivity extends BaseActivity implements OnItemClickListener {

    private static final String KEY_ICON = "mKeyIcon";
    private static final String KEY_NAME = "mKeyName";
    private int[] mIconIds = {
            R.drawable.ic_answer_exercises_everyday,
            R.drawable.ic_answer_exercises_weekly,
            R.drawable.ic_answer_exercises_special};
    private String[] mNames = {"每日一练", "每周练习", "专项练习"};
    private BaseQuickAdapter<Map<String, Object>, BaseViewHolder> mAdapter;

    private ExercisesDaily mExercisesDaily;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        for (int i = 0; i < mIconIds.length; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put(KEY_ICON, mIconIds[i]);
            item.put(KEY_NAME, mNames[i]);
            mAdapter.addData(item);
        }
        getStudentDailyPracticeConfig(false);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_answer_exercises;
    }

    @Override
    protected void initViews() {
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.set(0, 0, 0, DisplayUtil.dip2px(16f));
            }
        });
        mAdapter = new BaseQuickAdapter<Map<String, Object>, BaseViewHolder>(R.layout.item_list_type_answer_exercises) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, Map<String, Object> item) {
                int iconId = (int) item.get(KEY_ICON);
                baseViewHolder.setBackgroundResource(R.id.iv_icon, iconId);
                String name = (String) item.get(KEY_NAME);
                baseViewHolder.setText(R.id.tv_name, name);
            }
        };
        mAdapter.setOnItemClickListener(this);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.answer_exercises;
    }

    private void getStudentDailyPracticeConfig(boolean toH5Page) {
        addDisposable(RetrofitService.getNetService()
                .getStudentDailyPracticeConfig()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        mExercisesDaily = response.getData();
                        if (toH5Page) {
                            toDailyH5Page();
                        }
                    } else {
                        if (toH5Page)
                            showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (ClickCheck.isFastClick()) return;
        switch (position) {
            case 0:// 每日一练
                if (mExercisesDaily == null) {
                    getStudentDailyPracticeConfig(true);
                } else {
                    toDailyH5Page();
                }
                break;
            case 1:// 每周练习
                startActivity(new Intent(getActivity(), AnswerExercisesWeeklyActivity.class));
                break;
            case 2:// 专项练习
                startActivity(new Intent(getActivity(), AnswerExercisesSpecialActivity.class));
                break;
            default:
                break;
        }
    }

    private void toDailyH5Page() {
        try {
            String token = URLEncoder.encode(BaseApplication.getContext().getToken(), "UTF-8");
            List<Integer> quesLibIds = mExercisesDaily.getQuesLibIds();
            StringBuilder quesLibIdsBuilder = new StringBuilder();
            for (int i = 0; i < quesLibIds.size(); i++) {
                quesLibIdsBuilder.append(",").append(quesLibIds.get(i));
            }
            String url = WebViewHelper.getBaseUrl() + "propaganda/practiceQuestion?fromType=1&token=" + token +
                    "&dailyQuestionCount=" + mExercisesDaily.getDailyQuestionCount() + "&quesLibIds=" + quesLibIdsBuilder.substring(1) +
                    "&version=" + PackageUtils.getVersionName(getContext()) + "&exerciseType=1";
            Log.e("每日一练", url);

            SharedPreferences settingss = getActivity().getSharedPreferences("tryToSwitch", 0);
            int isAmazing = settingss.getInt("tryToSwitch", 0);
            if (isAmazing == 2) {
                //原生每日练习 梁尔宾
                Intent intent = new Intent(AnswerExercisesActivity.this, DailyPracticeActivity.class);
                intent.putExtra("quesLibIds", quesLibIdsBuilder.substring(1));
                intent.putExtra("dailyQuestionCount", mExercisesDaily.getDailyQuestionCount() + "");
                intent.putExtra("path", 0);
                startActivity(intent);
            } else {
                MyWebViewActivity.actionStart(getContext(), url, "每日一练", 1);
            }

            Log.e("dailyQuestionCount", quesLibIdsBuilder.substring(1));
            Log.e("dailyQuestionCount", mExercisesDaily.getDailyQuestionCount() + "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
